<template>
    <!-- 对话框表单 -->
    <!-- 建议使用 Prettier 格式化代码 -->
    <!-- el-form 内可以混用 el-form-item、FormItem、ba-input 等输入组件 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        @open="onOpen"
        width="50%"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '':'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <FormItem :label="t('付款项目')" type="remoteSelect" v-model="baTable.form.items!.project_id" prop="project_id" :input-attr="{ pk: 'ba_project.id', field: 'title', 'remote-url': '/admin/Project/index' }" :placeholder="t('Please select field', { field: t('付款项目') })" />
                    <FormItem :label="t('apply.payment.date')" type="date" v-model="baTable.form.items!.date" prop="date" :placeholder="t('Please select field', { field: t('apply.payment.date') })" />
                    <el-form-item :label="t('供应商')" prop="supplier_id">
                        <el-select filterable v-model="baTable.form.items!.supplier_id" placeholder="请选择供应商" size="large" style="width: 100%" @change="onSupplierChange">
                            <el-option v-for="item in supplierLists" :key="item.value" :label="item.company_name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="付款类目">
                        <div class="" :key="index" v-for="item,index in feeitemSets">
                            <el-row>
                                <el-col :span="15">
                                    <el-cascader 
                                        :props="{
                                            value: 'id',
                                            label: 'title',
                                            emitPath: false
                                        }" 
                                        v-model="item.feeitem_id"
                                        :options="feeitemLists" 
                                        :show-all-levels="false" 
                                        :filterable="true"
                                        :placeholder="t('Please select field', { field: t('付款类目') })"
                                        style="width:100%">
                                        </el-cascader>
                                </el-col>
                                <el-col :span="6">
                                    <el-input type="number" v-model.number="item.amount" @change="(val) => { feeitemHand(val, 'amount', index) }" placeholder="Please input" />
                                </el-col>
                                <el-col :span="3">
                                    <Icon name="el-icon-CirclePlus" color="#409eff" size="26" @click="addFeeitems" v-if="index == feeitemSets?.length -1"/>
                                    <Icon name="el-icon-Remove" color="#f56c6c" size="26" @click="delFeeitems(index)" v-else/>
                                </el-col>
                            </el-row>
                        </div>
                    </el-form-item>
                    <FormItem :label="t('apply.payment.pay_amount')" type="number" prop="pay_amount" :input-attr="{ step: 1, readonly: true }" v-model.number="baTable.form.items!.pay_amount" :placeholder="t('Please input field', { field: t('apply.payment.pay_amount') })" />
                    <el-form-item :label="t('apply.payment.pay_type')" prop="pay_type">
                        <el-select v-model="baTable.form.items!.pay_type" placeholder="请选择付款方式" size="large" style="width: 100%" @change="onPayTypeChange">
                            <el-option key="对公" label="对公" value="对公" />
                            <el-option key="对私" label="对私" value="对私" />
                        </el-select>
                    </el-form-item>
                    <FormItem :label="t('apply.payment.pay_time')" type="datetime" v-model="baTable.form.items!.pay_time" prop="pay_time" :placeholder="t('Please select field', { field: t('apply.payment.pay_time') })" />
                    <FormItem :label="t('apply.payment.account')" type="textarea" v-model="baTable.form.items!.account" prop="account" :placeholder="t('Please input field', { field: t('apply.payment.account') })" />
                    <FormItem :label="t('apply.payment.files')" type="files" v-model="baTable.form.items!.files" prop="files" />
                    <FormItem :label="t('apply.payment.remarks')" type="textarea" v-model="baTable.form.items!.remarks" prop="remarks" :input-attr="{ rows: 3 }" @keyup.enter.stop="" @keyup.ctrl.enter="baTable.onSubmit(formRef)" :placeholder="t('Please input field', { field: t('apply.payment.remarks') })" />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="onSubmit" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
interface feeitemSetsItem {
    feeitem_id:number 
    feeitem_name: string
    amount:number
}
import { ElMessage, type FormInstance, type FormItemRule } from 'element-plus'
import { inject, reactive, ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'
import { timeFormat } from '/@/utils/common'
import { getFeeitemList, getSupplier} from '/@/api/backend/index'

const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass
const { t } = useI18n()

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    
    project_id: [
        buildValidatorData({ name: 'required', title: t('apply.reimbursement.project_id') })
    ],
    date: [
        buildValidatorData({ name: 'required', title: t('apply.reimbursement.date') }),
        buildValidatorData({ name: 'date', title: t('apply.reimbursement.date') })
    ],
    feeitem_id: [
        buildValidatorData({ name: 'required', title: t('apply.reimbursement.feeitem_id') })
    ],
    amount: [
        buildValidatorData({ name: 'required', title: t('apply.reimbursement.date') }),
        buildValidatorData({ name: 'number', title: t('apply.reimbursement.amount') })
    ]
})

let feeitemLists: any[] = []
let supplierLists: any[] = []
let supplier: any = {}

const feeitemSets = ref<feeitemSetsItem[]>()
let feeitemListsAll: any[] = []

onMounted(() => {
    getFeeitemList().then(res => {
        const tempDatas: any[] = []
        res.data.list.forEach((item: any) => {
            feeitemListsAll.push(item)
            tempDatas.push({
                id: item.id,
                title: item.title,
                pid: item.pid,
                disabled: false,
                children: []
            })
            const index = tempDatas.length - 1
            item.children?.forEach((ele: any) => {
                feeitemListsAll.push(ele)
                tempDatas[index]['children'].push({
                    id: ele.id,
                    title: ele.title,
                    pid: ele.pid,
                    disabled: false,
                })
            })
        })
        feeitemLists = tempDatas
    })
    getSupplier({limit: 10000}).then((res: any) => {
        supplierLists = res.data.list
    })
})

const onOpen = () => {
    if(!baTable.form.items!.no) {
        baTable.form.items!.date = timeFormat(null, 'yyyy-mm-dd');
        baTable.form.items!.pay_type = '对公'
        feeitemSets.value = [{feeitem_id: 0, feeitem_name: '', amount: 0}]
    }    
}

const onSupplierChange = (value: any) => {
    supplier = supplierLists.find((p: any) => p.id == value)
    baTable.form.items!.account = `${supplier.account_name} ${supplier.account_bank} ${supplier.account_no} ${supplier.account_bank_name}`;
}

const onPayTypeChange = (value: any) => {
    console.log('value', value)
    if(value == '对公'){
        baTable.form.items!.account = `${supplier.account_name} ${supplier.account_bank} ${supplier.account_no} ${supplier.account_bank_name} `;
    } else {
        baTable.form.items!.account = `${supplier.account_bank} ${supplier.account_no} ${supplier.account_bank_name} ${supplier.person_name} ${supplier.contact_tel} ${supplier.person_idcard}`;
    }
}

const addFeeitems = () => {
    feeitemSets.value?.push({feeitem_id: 0, feeitem_name: '', amount: 0})
}

const delFeeitems = (index: number)=>{
    feeitemSets.value?.splice(index, 1)
    caclFeeitems()
}

const feeitemHand = (val:string|number, field: string, index: number) => {
    feeitemSets.value[index][field] = val
    caclFeeitems()
}

const caclFeeitems = () => {
    let amount = 0
    feeitemSets.value.forEach((item: feeitemSetsItem) => {
        amount += Number(item.amount)
    })
    baTable.form.items!.pay_amount = amount
}

const onSubmit = () => {
    for(let i = 0; i < feeitemSets.value?.length; i++){
        if(Number(feeitemSets.value[i]['feeitem_id']) <= 0){
            return ElMessage.error(`第${++i}项的费用项目未选择`)
        }
        // if(Number(feeitemSets.value[i]['amount']) <= 0){
        //     return ElMessage.error(`第${++i}项的费用金额不能小于0`)
        // }
    }
    feeitemSets.value?.forEach((item: feeitemSetsItem, index: number) => {
        item.feeitem_name = feeitemListsAll.find((p: any) => p.id == item.feeitem_id)['title']
    })
    baTable.form.items!.feeitems = feeitemSets.value
    baTable.onSubmit(formRef.value)
}
</script>

<style scoped lang="scss"></style>
